<?php
// +----------------------------------------------------------------------
// | 通用PHP框架 [ ThinkPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 郑州智众 [Paulxun@qq.com]
// +----------------------------------------------------------------------
// | 官方网站: https://www.zzmind.com
// +----------------------------------------------------------------------

namespace app\mall\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\mall\model\Goods as GoodsModel;
use app\mall\model\Order as OrderModel;
use app\user\model\Level as LevelModel;
use app\user\model\Member as MemberModel;
use app\user\model\Vip as VipModel;
use think\facade\Db;

/**
 * 订单默认控制器
 * @package app\merch\admin
 */
class Order extends Admin
{
    /**
     * 订单首页
     * @author PaulXun <paulxun@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);
		// 查询条件
		$map = $this->getMap();
        // 排序条件
		$order = $this->getOrder('id desc');
		
        // 数据列表
        $data_list = OrderModel::where($map)->order($order)->paginate(config('paginate'));

		$btnDel = [
		    'class' => 'btn btn-xs btn-default ajax-get confirm',
		    'icon'  => 'fa fa-times',
		    'title' => '撤销订单',
		    'href'  => url('delete', ['id' => '__id__']),
			'data-title' => '真的要撤销订单吗？',
			'data-tips' => '撤销订单将自动退款，且不可恢复！'
		];
        $btnLive = [
            'class' => 'btn btn-xs btn-default ajax-get confirm',
            'icon'  => 'fa fa-pencil',
            'title' => '驳回订单',
            'href'  => url('live', ['id' => '__id__']),
            'data-title' => '真的要驳回订单吗？',
            'data-tips' => '驳回订单将恢复正常订单！'
        ];

		$btnQuery = [
		    'class' => 'btn btn-xs btn-default ajax-get',
		    'icon'  => 'fa fa-fw fa-refresh',
		    'title' => '查询',
		    'href'  => url('query', ['out_trade_no' => '__out_trade_no__']),
		];
		// 导出按钮
		$btnExport = [
			'title' => '导出订单',
			'icon'  => 'fa fa-fw fa-file-excel-o',
			'class' => 'btn btn-primary',
			'href'  => url('export')
		];
		$js = <<<EOF
			<script type="text/javascript">
			$('input.form-control').attr("autocomplete","off");
			</script>
EOF;
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('订单管理') // 设置页面标题,
            ->setSearch(['out_trade_no' => '商户单号','uid'=>'用户ID','pay_name'=>'订单姓名']) // 设置搜索参数
            ->addColumns([ // 批量添加列
                ['id', 'ID'],
				['pay_price', '总金额', 'callback', function($value){
					return '￥' . $value / 100;
				}],
				['balance', '首购', 'callback', function($value){
					return '￥' . $value / 100;
				}],
				['second', '复购', 'callback', function($value){
					return '￥' . $value / 100;
				}],
				['realpay', '微信支付', 'callback', function($value){
					return '￥' . $value / 100;
				}],
				['out_trade_no', '商户单号'],
                ['create_time', '下单时间', 'datetime'],
				['pay_time', '支付时间', 'datetime'],
                ['pay_name', '订单姓名'],
				['uid', '会员ID/姓名', 'callback', function($value){
					$vip = VipModel::info($value);
					return $vip['member_id'].'/'.$vip['realname'];
				}],
				['status', '订单', 'status', '', OrderModel::status()],
				['update_time', '管理', 'callback', function($value, $data){
					return '<a href="'.url('detail', ['id' => $data['id']]).'">处理订单</a>';
				}, '__data__'],
                ['right_button', '操作', 'btn']
            ])
            // ->addTopButtons('enable,disable') // 批量添加顶部按钮
            //->addRightButtons('delete') // 批量添加右侧按钮
			->addTopButton('custom', $btnExport, true) // 添加导出按钮
			->addRightButton('custom', $btnQuery) //查询
			->addRightButton('custom', $btnDel)
            ->addRightButton('custom', $btnLive)
			->addFilterList('status', OrderModel::status())
			->hideCheckbox()
			->setColumnWidth(['id' => 60,'pay_price' => 60,'realpay' => 60, 'payer' => 120, 'create_time' => 80, 'pay_time' => 80])
			->addTimeFilter('create_time')
            ->setRowList($data_list) // 设置表格数据
			->setExtraJs($js)
            ->fetch(); // 渲染页面
    }

    /**
     * 订单退款
     * @param string $out_trade_no 订单out_trade_no
     * @return mixed
     * @throws \think\Exception
     */
    public function refund($out_trade_no = '')
    {
        if ($out_trade_no === 0) $this->error('参数错误');

		// 实例化模型
		$pay = new OrderModel;
		$return = $pay->refund($out_trade_no);
		if($return === false){
			$this->error($pay->getError());
		}else{
			$this->success('退款成功');
		}
    }
	/**
	 * 订单查询
	 * @param string $out_trade_no 订单out_trade_no
	 * @return mixed
	 * @throws \think\Exception
	 */
	public function query($out_trade_no = 0)
	{
	    if ($out_trade_no == 0) $this->error('商品未下单或订单未拉起支付');
	
		// 实例化模型
		$pay = new OrderModel;
		$return = $pay->tradeQuery($out_trade_no);
		if($return === false){
			$this->error($pay->getError());
		}else{
			$this->success('查询成功');
		}
	}
	/**
	 * 导出订单记录
	 * @param int $map 栏目id
	 * @return mixed
	 * @throws \think\Exception
	 */
	public function export()
	{
		if(request()->isPost()){
			$data = request()->post();
			// 查询条件
			$map =[];
			if(!isset($data['status'])) $this->error('请选择交易状态');
			if($data['status'] != 99)$map[] =['status', '=', $data['status']];
			
			if(!$data['date1'] || !$data['date2']) $this->error('时间区间必选');
			$from = strtotime($data['date1']);
			$to = strtotime($data['date2']) + 3600*24 - 1;
			if (($to - $from)/(3600*24) > 45)  $this->error('最多导出45天的订单数据');
			$map[] =['create_time', 'between', [$from, $to]];
			$return = [];
			// 排序条件
			$order = 'create_time desc';
			
			// 获取查询数据，数组形式
			$order_list =  OrderModel::where($map)->order($order)->select()->toArray();
			
			if(!$order_list) $this->error('该条件下无可导出数据');
            foreach ($order_list as $key => $value){
                // 实例化
                $order = new OrderModel;
                $detail =  $order->detail($value['id']);
                $uid = $detail['uid'];
                // 获取用户信息
                $user = MemberModel::where('id',$uid)->find();
                $user['level'] = 0;
                $vip = VipModel::where('member_id', $uid)->where('status', 1)->find();
                $user['group'] = LevelModel::level_list($vip['group']);
                $user['level'] = $vip['group'];
                $shop = LevelModel::shopConfig($vip['shop']);
                $user['shop'] = $shop['name'];
//                var_dump($vip['address']);exit;
                $order_list[$key]['nickname'] = $user['nickname'];
                $order_list[$key]['realname'] = $user['realname'];
                $order_list[$key]['mobile'] = $user['mobile'];
                $order_list[$key]['address'] = $vip['address'];
                $order_list[$key]['group'] = $user['group'];
                $order_list[$key]['shop'] = $user['shop'];

                $order_list[$key]['title'] = $detail['detail'][0]['title'];
                $order_list[$key]['pay_price'] = $value['pay_price'] / 100;
                $order_list[$key]['number'] = $value['number'];
                $order_list[$key]['realpay'] = $value['realpay'] / 100;
                $order_list[$key]['balance'] = $value['balance'] / 100;
                $order_list[$key]['second'] = $value['second'] / 100;
                $order_list[$key]['trade'] = (string)$value['out_trade_no'];
                $order_list[$key]['ex_com'] = (string)$value['ex_com'];
                $order_list[$key]['express'] = (string)$value['express'];
                $order_list[$key]['time'] = format_time($value['pay_time']);
                $order_list[$key]['status'] = OrderModel::status($value['status']);
            }
            $return['list'] = $order_list;
            // 设置表头信息（对应字段名,显示表头名称）
            $head[0] = [
                'id'		=> '订单ID',
                'nickname' 	=> '微信昵称',
                'realname' 	=> '姓名',
                'mobile' 	=> '手机号',
                'address' 	=> '地址',
                'group' 	=> '会员等级',
                'shop' 	=> '店铺等级',
                'title' 	=> '商品名称',
                'trade' 	=> '商户单号',
                'pay_price' => '交易金额（元）',
                'number'  	=> '商品数量',
                'realpay'  	=> '现金支付',
                'balance'  	=> '首购余额',
                'second'  	=> '复购金额',
                'uid' 		=> '用户',
                'ex_com' 	=> '快递公司',
                'express' 	=> '快递单号',
                'status' 	=> '状态',
                'time' 		=> '支付时间',
                'remark' 	=> '备注',
            ];
			// 向第一行插入表头
			$return['list'] = array_merge($head, $return['list']);
			
			// 表格筛选字段
			$return['field'] = [];
			foreach ($head[0] as $key => $value){
				$return['field'][] = $key;
			}
			
			$return['title'] = '订单'.$data['date1'].'_'.$data['date2'];
			// 返回数据（[导出文件名:title、字段信息:field、具体数据:list]）
			$this->success('导出成功', '', $return);
		}
		$js = <<<EOF
			<script type="text/javascript">
			$('input#date1').attr("autocomplete","off");
			$('input#date2').attr("autocomplete","off");
			</script>
EOF;
		// 设置表单
		$where =[
			['id', '>', 0],
		]; 
		$goods_list = GoodsModel::where($where)->column('title', 'id');
		return ZBuilder::make('form')
		->setPageTips('请按需求选择数据筛选', 'info')
		->setPageTitle('选择数据')
		->addFormItems([
		    ['select:8', 'gid', '选择商品', '不选择商品，将导出所有商品订单', $goods_list],
			['radio', 'status', '交易状态', '',[99 => '全部'] + OrderModel::status(), 99],
		])
		->addDaterange('date1,date2', '日期范围', '<span class="text-danger">最长跨度45天</span>')
		->layout(['ids' => 8, 'date1' => 8, 'date2' => 8])
		->hideBtn(['submit', 'back'])
		->addBtn('<button type="button" id="get_data" class="btn btn-info">导出数据</button>')
		->js('js/excel,js/export') // 引入外部excel.js文件
		->setExtraJs($js)
		->fetch();
	}
	// 根据商家获取终端
	public function detail($id = 0)
	{
		if ($id == 0) $this->error('参数错误');
		
		// 实例化
		$order = new OrderModel;
		$detail =  $order->detail($id);
		
		$info = VipModel::info($detail['uid']);
        $payer = MemberModel::getOpenid($detail['uid']);


		if (!$info) $this->error('该订单用户不存在');
		
		if ($detail !== false) {
			if (request()->isPost()) {
				$data = request()->post();

				$order = OrderModel::find($id);
				switch ($detail['status']) {
					case 1: 
					// $btn_title = '确认发货';
					if (empty($data['ex_com'])) $this->error('请选择快递公司');
					if ($data['express'] == '') $this->error('请输入运单号');
					$order->ex_com = $data['ex_com'];
					$order->express = $data['express'];
					$order->send_time = time();
					$order->status = 2;
					$order->save();

                    $sendData = [
                        'template_id'   => 'XbmmvP9HIu1wXt55yilyLAZ6RNAc15q59EF6t3-jLzo',//模板消息ID
                        'touser'    => $payer,//用户openid
                        'data'=>[
                            'first'=>[
                                'value'=>'我们已收到您的货款，开始为您打包商品，请耐心等待: )',
                                'color'=>'#000000',
                            ],
                            'keyword1'=>[
                                'value'=>$order['out_trade_no'],//订单编号
                                'color'=>'#000000'
                            ],
                            'keyword2'=>[
                                'value'=>$data['ex_com'],//物流服务
                                'color'=>'#000000'
                            ],
                            'keyword3'=>[
                                'value'=>$data['express'],//快递单号
                                'color'=>'#000000'
                            ],
                            'keyword4'=>[
                                'value'=>$info['realname'].'-亲爱的主上大人，您的订单已出库',//订单编号
                                'color'=>'#000000'
                            ],
                            'remark'=>[
                                'value'=>'欢迎下次选购！',//描述
                                'color'=>'#173177',
                            ],
                        ]
                    ];
                    $this->template($sendData);

					break;
					case 2:
					// $btn_title = '确认收货';
					$orderModel = new OrderModel;
					$return = $orderModel->action($id);
					if ($return == false) {
						$this->error($orderModel->getError());
					}
					break;
					case 3:
					// $btn_title = '确定';
					break;
					default:
					return $this->delete($id);
				}
				$this->success('处理成功', cookie('__forward__'));
			}
			switch ($detail['status']) {
				case 1: 
				$btn_title = '确认发货';
				break;
				case 2:
				$btn_title = '确认收货';
				break;
				case 3:
				$btn_title = '确定';
				break;
				default:
				$btn_title = '取消订单';
			}
			$vip = VipModel::getAddress($detail['uid']);
            $detail_listed = Db::name('mall_order_detail')->where('oid', '=', $id)->find();
//			var_dump($detail_listed);exit;
            $info = [
				'print' => ['title' => '打印发货单', 'icon' => 'fa fa-fw fa-print', 'class' => 'btn-success',],
				'create_time' => format_time($detail['create_time']),
				'pay_time' => format_time($detail['pay_time']),
				'send_time' => $detail['send_time'] == 0 ? '待发货' :format_time($detail['send_time']),
				'pay_price' => '￥' .$detail['pay_price'] / 100,
				'money' => '首购：￥' . $detail['balance'] / 100 . '，复购：￥' . $detail['second'] / 100,
				'realpay' => '￥' .$detail['realpay'] / 100,
                'remark' => $detail_listed['remark'],
				'express' => $detail['express'],
				'ex_com' => $detail['ex_com'],
			];
			$title = '商品发货单：'. $detail['out_trade_no'];
			$table_data = [];
			foreach ($detail['detail'] as $value) {
				$table_data[] = [
					$value['title'],
					$value['number'],
					'￥'.$value['pay_price'] / $value['number'] / 100,
				];
			}
			$table_data[] = ["&nbsp;[3]"];
			$table_data[] = ['收货地址', $vip['province'].$vip['city'].$vip['country'].$vip['address'] ."<br>". $vip['name'] ."&nbsp;". $vip['mobile']. "&nbsp;[2]"];
			$table_head = [
				['商品名称', '数量', '单价'],
			];
			
			// 设置下部表单
			$fields = [
				['static:3', 'create_time', '下单时间'],
				['static:3', 'pay_time', '支付时间'],
				['static:6', 'send_time', '发货时间'],
				['static:3', 'pay_price', '总支付金额'],
				['static:3', 'money', '余额支付'],
				['static:6', 'realpay', '微信支付'],
                ['static:6', 'remark', '订单备注'],
			];
			if ($detail['status'] >= 1) {
				$fields[] = ['select:8', 'ex_com', '快递公司', '', OrderModel::express()];
				$fields[] = ['text:8', 'express', '快递运单号', '快递发货的运单号'];
			}
			$js = <<<EOF
			<script type="text/javascript">
			$("#print").on('click', function(){
				$("#table-order").print();
			})
			</script>
EOF;
			// 使用ZBuilder快速创建表单
			return ZBuilder::make('form')
				->addFormItems([ // 批量添加表单项
				        ['complexTable:8', 'order', $title, $table_data, $table_head],
						['button', 'print', $info['print']]
				    ])
				->addFormItems($fields)
				// ->addBtn('<button type="button" id="print" class="btn btn-minw btn-primary ajax-post">打印发货单</button>')
				->layout(['cid' => 8, 'title' => 8, 'avatar' => 12,'zhiwu' => 8, 'mobile' => 8, 'code' => 8, 'uid' => 8])
			    ->setFormData($info)
				->js('js/jQuery.print')
				->setExtraJs($js)
				->setBtnTitle('submit', $btn_title)
			    ->fetch();
		} else {
			$this->error($order->getError());
		}
	}
    /**
     * 删除订单
     * @author PaulXun <paulxun@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delete($id = 0)
    {
		// 获取订单信息
		$order = OrderModel::where('id', '=', $id)->find();

		if($order->status == 5){
			// 实例化
			$order = new OrderModel;
			$return =  $order->cancel($id);
			if ($return === false) {
				$this->error($order->getError());
			}else{
				$this->success('撤销成功', cookie('__forward__'));
			}
		}else{
			$this->error('该订单不可撤销');
		}
    }

    /**
     * 驳回订单
     * @author PaulXun <paulxun@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function live($id = 0)
    {
        // 获取订单信息
        $order = OrderModel::where('id', '=', $id)->find();

        if($order->status == 5){
            // 实例化
            $order = new OrderModel;
            $return =  $order->cancel_live($id);
            if ($return === false) {
                $this->error($order->getError());
            }else{
                $this->success('驳回成功', cookie('__forward__'));
            }
        }else{
            $this->error('该订单不可撤销');
        }
    }

    /**
     * 启用订单
     * @param array $ids 订单id
     * @author PaulXun <paulxun@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function enable($ids = [])
    {
        return $this->setStatus('enable');
    }

    /**
     * 禁用订单
     * @param array $ids 订单id
     * @author PaulXun <paulxun@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function disable($ids = [])
    {
        return $this->setStatus('disable');
    }

    /**
     * 设置订单状态：禁用、启用
     * @param string $type 类型：delete/enable/disable
     * @param array $record
     * @author PaulXun <paulxun@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function setStatus($type = '', $record = [])
    {
        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
		
		// 清除缓存
		cache('merch_child_list', null);
		cache('merch_child_column', null);
		foreach ($ids as $id){
			cache('merch_child_info_'. $id, null);
		}
        $status = is_array($ids) ? '' : $ids;
        $names  = ChildModel::where('id', 'in', $ids)->column('name');
        return parent::setStatus($type, ['merch_child_'.$type, 'merch_child', $status, UID, implode('、', $names)]);
    }

    /**
     * 快速编辑
     * @param array $record 行为日志
     * @author PaulXun <paulxun@qq.com>
     * @return mixed
     */
    public function quickEdit($record = [])
    {
        $id      = input('post.pk', '');
        $field   = input('post.name', '');
        $value   = input('post.value', '');
		// 清除缓存
		cache('merch_child_list', null);
		cache('merch_child_column', null);
		cache('merch_child_info_'. $id, null);
        $config  = ChildModel::where('id', $id)->value($field);
        $details = '字段(' . $field . ')，原值(' . $config . ')，新值：(' . $value . ')';
        return parent::quickEdit(['merch_child_edit', 'merch_child', $id, UID, $details]);
    }
}
